<?php
use Illuminate\Support\Str;

function renderErrorJson($errno = 0, $msg = '', $data = array())
{
    $json = [
        'errorCode'     => $errno,
        'resultData'    => $data,
        'errorMessage'  => $msg,
    ];
    return sendJson($json);
}

function renderSuccessJson($data = array(), $errno = 0, $msg = 'success')
{
    $json = [
        'errorCode'     => $errno,
        'resultData'    => $data,
        'errorMessage'  => $msg,
    ];
    return sendJson($json);
}

function sendJson($array)
{
    if (isset(request()->header()['x-show-error'])) {
        return response($array, 200, [
            'X-SHOW-ERROR' => 1
        ]);
    }
    return response()->json($array);
}

function toCamelCaseKey($arr): array
{
    $tmp = [];
    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $v = toCamelCaseKey($v);
            }
            if (strpos($k, '_')) {
                $key = ucwords(str_replace('_', ' ', $k));
                $key = str_replace(' ', '', lcfirst($key));
                $tmp[$key] = $v;
            } else {
                $tmp[$k] = $v;
            }
        }
    }
    return $tmp;
}

function toSnakeKey(array $arr)
{
    $tmp = [];

    foreach ($arr as $key => $value) {
        $tmp[Str::snake($key)] = $value;
    }

    return $tmp;
}
